<template>
  <div class="container">
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="活动名称：" prop="name">
            <el-input v-model.trim="form.name" placeholder="活动名称："></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="首页图：" prop="index_image">
            <UploadImageInfo :imageWidth="325" :imageHeight="127" :limit="500" suggestInfo="建议：尺寸650x254像素(等比例亦可)，大小500k以下。" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="index_image" v-model:form="form" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="主图：" prop="image">
            <UploadImageInfo :imageWidth="375" :imageHeight="265" :limit="300" suggestInfo="建议：尺寸750x530像素(等比例亦可)，大小300k以下。" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="image" v-model:form="form" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left"><span class="title-left-color">商品信息</span></el-divider>
      <el-space wrap class="mb20">
        <el-button type="primary" :icon="Plus" :disabled="disabledbtn" @click="handleAddGoodsData">新增</el-button>
        <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="batchDeleteGoods">
          <template #reference>
            <el-button type="danger" :icon="Delete" :disabled="disabledbtn">批量删除</el-button>
          </template>
        </el-popconfirm>
      </el-space>
      <el-table :data="form.goods_list" border class="table" ref="selectGoodsMultipleTableRef" :reserve-selection="true">
        <el-table-column type="index" align="center"> </el-table-column>
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="goods_image" label="图片" width="150" align="center">
          <template #default="scope">
            <el-image style="width: 60px; height: 60px" :src="IMG_URL + scope.row.goods_image"> </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="goods_name" label="商品名称" align="center"> </el-table-column>
        <el-table-column prop="red_packet_price" label="零售价" align="center"> </el-table-column>
        <el-table-column prop="red_packet_price" label="最多可抵扣红包" align="center"> </el-table-column>
        <el-table-column prop="official_price" label="淘宝价" align="center"> </el-table-column>
        <el-table-column prop="sales_actual" label="已售数量" align="center"> </el-table-column>
        <el-table-column prop="sort" label="排序" align="center">
          <template #default="scope">
            <el-input v-model.trim="scope.row.sort" placeholder="请输入内容" @change="handleLocalSort"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <div class="mlr10 display-inline-block">
              <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="handleDeleteGoods(scope.row)">
                <template #reference>
                  <el-button link :icon="Delete" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>

  <SelectMallGoodsDialog :selectCategories="selectCategories" v-model:editVisible="editVisible" @handleSuccess="handleSelectSuccess" />
</template>

<script setup lang="ts">
import UploadImageInfo from "@/components/common/UploadImageInfo.vue";
import SelectMallGoodsDialog from "@/components/redPacketMallManage/mallGoodsInfo/SelectMallGoodsDialog.vue";
import { IMG_URL } from "@/utils/config";
import { Delete, Plus } from "@element-plus/icons-vue";
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import type { TableInstance } from "element-plus";
import { useState } from "@/hooks/useState.ts";
import type { IPurchaseGoodsItem } from "@/types/redPacketMallManage/mallRedPacketPurchase";
import type { IMallCategory } from "@/types/mallCategory";
import { getMallCategoryInfo } from "@/utils/api/mallCategory";
import type { IMallGoodsListVO } from "@/types/redPacketMallManage/mallGoods";
import type { IMallSpecialDetailVO, IMallSpecialGoodsList } from "@/types/redPacketMallManage/mallSpecial";
import { commonMallSpecialInfo, getMallSpecialByIdInfo } from "@/utils/api/mallSpecial";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  id: number;
}
const { id } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();
/* 商品分类 */
const selectCategories = ref<Array<IMallCategory>>([]);
const isDisabledbtn = ref(false);
const editVisible = ref(false);
const checkAll = ref(false);
const queryDate = ref<Array<string>>([]);
const formRef = useTemplateRef("formRef");
const selectGoodsMultipleTableRef = ref<TableInstance>();
const methodType = ref<postOrPutType>("PUT");
const form = reactive<IMallSpecialDetailVO>({
  id: 0,
  image: "",
  name: "",
  goods_list: [],
  index_image: ""
});
const rules = reactive({
  name: [{ required: true, message: "请填写活动名称", trigger: "blur" }],
  start_time: [{ required: true, message: "请选择活动时间", trigger: "blur" }],
  index_image: [{ required: true, message: "请上传首页图", trigger: "blur" }],
  image: [{ required: true, message: "请上传主图", trigger: "blur" }]
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      form.id = newValue;
      handleGetMallRedPacketPurchaseByIdInfo(id);
    }
  }
);

/* 获取分类信息 */
function handleGetMallCategory() {
  getMallCategoryInfo<Array<IMallCategory>, unknown>()
    .then(res => {
      selectCategories.value = res.result;
    })
    .finally(() => {});
}
/* 获取活动详情信息 */
function handleGetMallRedPacketPurchaseByIdInfo(id: number) {
  toggleState(true);
  getMallSpecialByIdInfo<IMallSpecialDetailVO, HasId>({ id })
    .then(res => {
      form.id = res.result.id;
      form.image = res.result.image;
      form.name = res.result.name;
      form.index_image = res.result.index_image;
      form.goods_list = res.result.goods_list;
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  checkAll.value = false;

  form.id = 0;
  form.goods_list = [];
  queryDate.value = [];
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonMallSpecialInfo(form, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}
/* 本地商品排序 */
function handleLocalSort() {
  form.goods_list.sort((a: IMallSpecialGoodsList, b: IMallSpecialGoodsList) => b.sort - a.sort);
}
/* 打开模态框选择新增商品 */
function handleAddGoodsData() {
  editVisible.value = true;
}
/* 批量删除商品信息 */
function batchDeleteGoods() {
  let selection = selectGoodsMultipleTableRef.value!.store.states.selection.value;
  if (selection.length === 0) {
    ElMessage.warning("请至少选择一条数据");
    return;
  }
  for (const item of selection) {
    handleDeleteGoods(item);
  }
}
/* 删除商品信息 */
function handleDeleteGoods(row: IPurchaseGoodsItem) {
  const index = form.goods_list.findIndex((item: IMallSpecialGoodsList) => item.goods_id === row.goods_id);
  if (index != -1) {
    form.goods_list.splice(index, 1);
  }
}

/* 选中数据 */
function handleSelectSuccess(data: IMallGoodsListVO[]) {
  for (const item of data) {
    if (!handleIsSelectedGoods(item)) {
      handleAddGoodsList(item);
    }
  }

  handleLocalSort();
}
/* 判断 goods_list是否已经选中过该商品了*/
function handleIsSelectedGoods(item: IMallGoodsListVO) {
  for (let i = 0; i < form.goods_list.length; i++) {
    if (form.goods_list[i].goods_id === item.id) {
      return true;
    }
  }
  return false;
}
/* 为活动添加商品 */
function handleAddGoodsList(data: IMallGoodsListVO) {
  form.goods_list.push({
    goods_id: data.id,
    goods_name: data.goods_name,
    official_price: data.official_price,
    red_packet_price: data.red_packet_price,
    goods_image: data.goods_image,
    sort: 0,
    retail_price: data.retail_price,
    sales_initial: data.sales_initial,
    stock_total: data.stock_total,
    sales_actual: ""
  });
}

handleGetMallCategory();
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
